package com.changli02.tcpudp;

import org.junit.Test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPTest {



    @Test
    public void send() throws Exception {
        //1.
        DatagramSocket ds = new DatagramSocket();
        //2.
        InetAddress inet = InetAddress.getByName("127.0.0.1");
        int port = 8081;
        byte [] buffer = "我踏马来辣".getBytes("utf-8");
        DatagramPacket dp = new DatagramPacket(buffer,0,buffer.length,inet,port);
        //3.
        ds.send(dp);
        ds.close();

    }

    @Test
    public void receive() throws Exception {

        //1.
        int port = 8081;
        DatagramSocket ds = new DatagramSocket(port);

        //2.
        byte[] buffer = new byte[1024*64];
        DatagramPacket dp = new DatagramPacket(buffer,0,buffer.length);

        //3.
        ds.receive(dp);

        //4.
        String str = new String(dp.getData(),0,dp.getLength());
        System.out.println(str);

        ds.close();




    }

}

